$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'quoteFastPrintMaterial/quotefastprintmaterial/list',
        datatype: "json",
        colModel: [
			{ label: 'id', name: 'id', index: 'id', width: 60, key: true ,hidden:true},
			{ label: '工厂id', name: 'factoryId', index: 'factory_id', width: 80,hidden:true },
            { label: '工厂名称', name: 'factoryName', index: 'factory_name', width: 80 },
			{ label: '选项id', name: 'optionId', index: 'option_id', width: 80,hidden:true },
            { label: '选项名称', name: 'optionName', index: 'option_name' },
			/*{ label: '是否启用', name: 'display', index: 'display', width: 80,align: 'center',
                formatter: function (value, options, row) {
                    var actions = [];
                    if(value){
                        actions.push('<label class="iSwitch"> <input type="checkbox"  onclick="vm.updatedisplay('+row.id+')" checked> <i></i></label>');
                    }else{
                        actions.push('<label class="iSwitch"> <input type="checkbox" onclick="vm.updatedisplay('+row.id+')"> <i></i></label>');
                    }
                    return actions.join('  ');
                }},*/
            { label: '操作', name: 'option' , align: 'center',width: 100,
                formatter:function(value, options, row){
                    var actions = [];
                    // 查看详情
                    actions.push('<a href="javascript:void(0);" class="btn btn-xs btn-success"  onclick="return vm.detail('+ row.optionId +');">查看详情</a>') ;
                    return actions.join('  ');
                }
            },
        ],
		viewrecords: true,
        height: window.innerHeight - 120,
        rowNum: 50,
		rowList : [25,50,100],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
        //打印机弹窗
        dialogVisible: false,
        //修改弹窗flag
        updateFlag:false,
		title: null,
        quoteFastPrintMaterial: {},
        quoteOptionNameList:[],
        quoteOptionName2List:[],
		materialSelectRows:[],
        optionSelectRows:[],
        printSelectRows:[],
        //快印打印机集合:
        printList:[],
		//查看详情后的optionName2
        detailOptionName2List:[],
        //封装生成组合的所有参数:
        quoteFastPrintGroupPrice:[],
        //已勾选的选项索引。用于回选
        indexList:[],
        e: {
            /* 打印机单双面类型 */
            singlepairTypeEnum: [],
        }
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			//清空之前的数据
            vm.quoteOptionNameList=[],
            vm.quoteOptionName2List=[];
			//查询所有材料列表
            var url = "quoteFastPrintMaterial/quotefastprintmaterial/findAllMaterial";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                success: function(r){
                   vm.quoteOptionNameList=r.quoteOptionNameList;
                }
            });
			vm.showList = false;
			vm.title = "新增";
            vm.quoteFastPrintMaterial = {};
		},
		update: function (event) {
		    //先判断有无勾选
           if(vm.materialSelectRows.length<1){
               alert("请至少选择一行");
               return;
           }
            //获取选中的行
            var idArray=[];
            for(var i=0;i<vm.materialSelectRows.length;i++){
                idArray.push(vm.materialSelectRows[i].id);
            }
            var ids=idArray.join(',');
            var url = "quoteFastPrintMaterial/quotefastprintmaterial/update/"+ids;
            $.ajax({
                type: "GET",
                url: baseURL + url,
                contentType: "application/json",
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.updateFlag=false;
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
		},
		save: function (event) {
			//获取选中的行
            var idArray=[];
            for(var i=0;i<vm.materialSelectRows.length;i++){
                idArray.push(vm.materialSelectRows[i].id);
            }
			var ids=idArray.join(',');
			var url = "quoteFastPrintMaterial/quotefastprintmaterial/save/"+ids;
			$.ajax({
				type: "GET",
			    url: baseURL + url,
                contentType: "application/json",
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
            var optionIds = new Array();
            for (var i = 0; i < ids.length; i++) {
                //选中行的optionid
                var optionid = $("#jqGrid").getCell(ids[i], "optionId");
                //建一个数组，把选中行的option_id添加到这个数组中去。
                optionIds[i] = optionid;
            }
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "quoteFastPrintMaterial/quotefastprintmaterial/delete",
                    contentType: "application/json",
				    data: JSON.stringify(optionIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
                                vm.detailOptionName2List=[];
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
        //获取已选和未选的材料选项
		getInfo: function(id){
            var id = getSelectedRow();
            if(id == null){
                return ;
            }
            vm.updateFlag = true;
            //先清空之前的数据
            vm.indexList=[];
            vm.quoteOptionName2List=[];
			$.get(baseURL + "quoteFastPrintMaterial/quotefastprintmaterial/info/"+id, function(r){
                if(r.code == 0) {
                    vm.quoteOptionName2List = r.quoteOptionName2List;
                    vm.indexList = r.indexList;
                    vm.quoteFastPrintMaterial.optionName= vm.quoteOptionName2List[0].optionName;
                    vm.select();
                }
            });
		},
        //修改时候自动勾选已经选过的
       select:function(){
            setTimeout(() => {
                for(var i=0;i< vm.indexList.length;i++){
                    this.$refs.updateTable.toggleRowSelection(vm.quoteOptionName2List[ vm.indexList[i]]);
                }
            },0)
        },
        //关闭修改窗体:
        closeUpdateDialog:function(){
            this.$confirm('您确定关闭吗？').then(()=> {
                vm.updateFlag=false;
            })
        },
		reload: function (event) {

            vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		},
		findAllOptionName2: function (optionName) {
            var url =  "quoteFastPrintMaterial/quotefastprintmaterial/findAllOptionName2";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.quoteFastPrintMaterial),
                success: function(r){
                  vm.quoteOptionName2List=r.quoteOptionName2List;
                }
            });
        },
		//获取材料table中所有选中的option.id
        handleMaterialSelection:function(val) {
            vm.materialSelectRows=val;
        },detail:function (optionId) {
           $.get(baseURL + "quoteFastPrintMaterial/quotefastprintmaterial/detail/"+optionId, function(r){
                vm.detailOptionName2List = r.detailOptionName2List;
            });
        },
        //详情table选中处理
        handleOptionSelection:function (val) {
            vm.optionSelectRows=val;
        },
        //生成组合中的打印机勾选
        handlePrintListSelection:function(val){
            vm.printSelectRows=val;
        },
        //弹出生成组合框
        generateDialog:function () {
            if(vm.optionSelectRows<1){
                alert("请至少选择一项");
                return;
            }
            vm.dialogVisible = true
            //否则向后台发起请求,查询这个工厂所有快印打印机信息
            $.get(baseURL + "quoteFastPrintMaterial/quotefastprintmaterial/printList", function(r){
                vm.printList=r.printList;
                vm.singlepairTypeEnum=r.singlepairTypeEnum;
            });
        },
        //关闭生成组合框
        cancelDialog:function() {
            this.$confirm('您确定关闭吗？').then(()=> {
                vm.quoteFastPrintGroupPrice=[];
            vm.dialogVisible = false;
            })
        },
        //确定生成组合
        generateGroup:function () {
		    if(vm.printSelectRows.length==0){
		        alert("请至少选择一行数据");
		        return;
            }
            var url =  "quoteFastPrintMaterial/quotefastprintmaterial/generateGroup";
            vm.quoteFastPrintGroupPrice.push(vm.printSelectRows);
            vm.quoteFastPrintGroupPrice.push(vm.optionSelectRows);
            console.log(vm.quoteFastPrintGroupPrice);
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.quoteFastPrintGroupPrice),
                success: function(r){
                    if(r.code == 0){
                        alert('操作成功', function(index){
                            vm.quoteFastPrintGroupPrice=[];
                            vm.dialogVisible = false;
                            $("#jqGrid").trigger("reloadGrid");
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        //修改右侧table是否启用
        updateDisplay:function(id){
            $.get(baseURL + "quoteFastPrintMaterial/quotefastprintmaterial/updateDisplay/"+id, function(r){
                if(r.code == 0){
                    alert('操作成功');
                }else{
                    alert(r.msg);
                }
            });
        }
	}
});